package cn.bdqn.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.bdqn.bean.User;
import cn.bdqn.service.UserService;
import cn.bdqn.service.impl.UserServiceImpl;
import cn.bdqn.util.Constant;
import cn.bdqn.util.PageUtil;

public class UserListServlet extends HttpServlet {

	/**
		 * The doGet method of the servlet. <br>
		 *
		 * This method is called when a form has its tag value method equals to get.
		 * 
		 * @param request the request send by the client to the server
		 * @param response the response send by the server to the client
		 * @throws ServletException if an error occurred
		 * @throws IOException if an error occurred
		 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		doPost(request, response);
	}

	/**
		 * The doPost method of the servlet. <br>
		 *
		 * This method is called when a form has its tag value method equals to post.
		 * 
		 * @param request the request send by the client to the server
		 * @param response the response send by the server to the client
		 * @throws ServletException if an error occurred
		 * @throws IOException if an error occurred
		 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		
		UserService service = new UserServiceImpl();
		PageUtil pageUtil = new PageUtil();
		String userName = request.getParameter("userName");
		//从前台获取当前页信息
		String currentPage = request.getParameter("pageIndex");
		//分页四要素
		int pageIndex = 1;
		if(currentPage != null){
			pageIndex = Integer.parseInt(currentPage);
		}else{
			pageIndex = 1;
		}
		int pageSize = Constant.PAGE_SIZE;
		int totalCount = 0;
		
		//给pageUtil赋值
		pageUtil.setPageIndex(pageIndex);
		pageUtil.setPageSize(pageSize);
		List<User> userList = null;
		if(userName==null){
			userName="";
		}
		User user = new User();
		user.setUserName(userName);
		totalCount = service.getCount(user);
		pageUtil.setTotalCount(totalCount);
		userList = service.getList(user, pageIndex, pageSize);
		//获取总页数
		int totalPages = pageUtil.getTotalPages();
		//把结果添加到作用域中
		request.setAttribute("userList", userList);
		request.setAttribute("pageIndex", pageIndex);
		request.setAttribute("totalPages", totalPages);
		request.setAttribute("totalCount", totalCount);
		System.out.println();
		//转发到userList.jsp
		request.getRequestDispatcher("/jsp/userList.jsp").forward(request,response);
		
		
	}

}
